<!-- 这是父组件 -->
<template>
    <div class="cpList">
        <div class="header">
            <van-nav-bar :title="`${route.query.title}已出库`" left-arrow @click-left="handleLeft" />
        </div>
        <OperationTimeChoice class="cpList_date" title="出库时间" v-model:value="date" @confirm="dateConfirm" />
        <SelectedItems type="3" v-model:putStatus="queryParams.putStatus" v-model:outType="queryParams.outType"
            @onSelect="onRefresh" />
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="flex: 1;min-height: 0;">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                        <van-image :src="nothingData"></van-image>
                        <div class="nothing_font">暂无数据</div>
                    </div>
                </template>
                <div class="selectedProducts">
                    <SelectedItems type="2" :status="true" v-for="item in list" :key="item.id" :datas="item"
                        @click="handleListClick(item)" />
                </div>
            </van-list>
        </van-pull-refresh>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// api
import { selectOutById } from '@/api/operation/index'
// 组件
import OperationTimeChoice from '../components/operationTimeChoice/index.vue'
import SelectedItems from '../components/selectedItems/index.vue'
// 图片
import nothingData from '@/assets/porduct/icon_zanwushuju.png'

const route = useRoute()
const router = useRouter()
const formatDate = (date: any) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
function getPastDate(days) {
    const today = new Date();
    const pastDate = new Date(today);
    pastDate.setDate(today.getDate() - days);
    return pastDate;
}

const date = ref([formatDate(getPastDate(30)), formatDate(new Date())])

const refreshing = ref(false);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)
const serchFlag = ref(true)
const loading = ref(false);
const finished = ref(false);
const list = ref<any[]>([]);
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    outStartTime: '',
    outEndTime: '',
    putStatus: '',
    outType: '',
});
const vantListScrollTop = ref<any>(0) // 滚动位置

// 在组件挂载完成后添加事件监听器
onMounted(() => {
    functionScroll('init')
})
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})

/** 查询商品列表 */
const getList = async () => {
    refreFlag.value = false
    queryParams.value.outStartTime = date.value[0]
    queryParams.value.outEndTime = date.value[1]
    const res = await selectOutById({ ...queryParams.value, stockDeptId: route.query.stockDeptId });
    setTimeout(() => {
        refreFlag.value = true
        // 空数据 停止加载
        if (res.rows.length == 0) {
            list.value = [];
            serchFlag.value = true;
            finished.value = true;
            return;
        }
        // 有数据 赋值列表 加载状态结束
        res.rows.forEach((item) => {
            finished.value = false;
            list.value.push(item);
        });
        loading.value = false;
        refreshing.value = false;
        serchFlag.value = true;
        // 如果list长度大于等于总数据条数，数据全部加载完成
        if (list.value.length >= res.total) {
            finished.value = true; //结束加载
        }
        // 解决快速切换tab导致的列表商品混乱问题
        if (queryParams.value.pageNum == 2 && queryParams.value.auditStatus) {
            list.value = list.value.filter((item) => {
                return item.auditStatus == queryParams.value.auditStatus
            })
        }

    }, 400);
};
/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        serchFlag.value = false
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};

const handleLeft = () => {
    router.back()
}

const handleListClick = (item: any) => {
    router.push({
        path: '/cpListLook',
        query: {
            rowData: JSON.stringify(item),
            title: route?.query?.title
        }
    })
}
const dateConfirm = () => {
    onRefresh()
}
</script>
<style lang="less" scoped>
.cpList {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    display: flex;
    background: #F6FAFF;
    flex-flow: column;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .cpList_date {
        margin: 10px 0;
    }


    .selectedProducts {
        width: 100%;
        box-sizing: border-box;
        background: #F6FAFF;
        padding: 0 10px 10px;
    }
}

:deep(.van-pull-refresh) {
    overflow: scroll;
}
</style>
